import json
import base64
import urllib.parse

from django.shortcuts import render, Http404
from django.http.response import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt

from .models import GameSave
from Lold.settings import IS_PYTHONANYWHERE


def get_post(request):
    try:
        post = json.loads(request.body.decode())
        user_id, data = (int(post.get('id')),
                         urllib.parse.unquote(base64.b64decode(post.get('data', b'')).decode()))
    except BaseException:
        return -1, ''
    else:
        return user_id, data


@login_required
def main(request):
    context = {
        'id': request.user.id,
        'is_pythonanywhere': IS_PYTHONANYWHERE,
    }
    return render(request, 'game/main.html', context=context)


@require_POST
@csrf_exempt
def set(request):
    try:
        user_id, data = get_post(request)
        user = get_user_model().objects.get(id=user_id)
        save, _ = GameSave.objects.get_or_create(owner=user)
        save.data = data
        save.save()
    except BaseException as e:
        print(e)
    return HttpResponse()


@require_POST
@csrf_exempt
def get(request):
    try:
        user_id, _ = get_post(request)
        user = get_user_model().objects.get(id=user_id)
        save, _ = GameSave.objects.get_or_create(owner=user)
        return HttpResponse(base64.b64encode(save.data.encode()))
    except BaseException as e:
        print(e)
        raise Http404
